package com.awardsystem.Controller;

import com.alibaba.fastjson.JSONObject;
import com.awardsystem.Service.AchievementService;
import com.awardsystem.Service.PatentService;
import com.awardsystem.Service.SCIService;
import com.awardsystem.Service.UserService;
import com.awardsystem.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@CrossOrigin
public class AchievementController {
    @Autowired
    AchievementService achievementService;
    @Autowired
    SCIService sciService;
    @Autowired
    PatentService patentService;
    @Autowired
    UserService userService;

    //添加成就
    @PostMapping("/addAchievement")
    public JSONObject addAchievement(@RequestBody JSONObject params){
        JSONObject ret=new JSONObject();
        String name=params.getString("name");
        String context= params.getString("context");
        LocalDate addtime = LocalDate.parse(params.getString("addtime"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String author = params.getString("author");
        String leader = params.getString("leader");
        String level = params.getString("level");
        if(achievementService.findAchievementByName(name)!=null) {
            ret.put("success", false);
            ret.put("exc", "禁止重复添加");
        }else{
            Achievement achievement=new Achievement();
            achievement.setName(name);
            achievement.setContext(context);
            achievement.setAddtime(addtime);
            achievement.setAuthor(author);
            achievement.setLeader(leader);
            achievement.setLevel(level);
            achievementService.addAchievement(achievement);
            int id = achievementService.findAchievementByName(name).getId();
            HashMap<String,Object> res = new HashMap<String ,Object>();
            res.put("id",id);
            ret.put("success",true);
            ret.put("data",res);
        }
        return ret;
    }

    //更新成就
    @PostMapping("/updateAchievement")
    public JSONObject updateAchievement(@RequestBody JSONObject params){
        JSONObject ret=new JSONObject();
        int id=params.getInteger("id");
        String name = params.getString("name");
        String context= params.getString("context");
        LocalDate addtime = LocalDate.parse(params.getString("addtime"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String author = params.getString("author");
        String leader = params.getString("leader");
        String level = params.getString("level");
        List<Integer>  useridList = params.getObject("relatedUser",List.class);
        List<Integer> patentidList = params.getObject("relatedPatent",List.class);
        List<Integer> sciidList = params.getObject("relatedSCI",List.class);
        Achievement achievement = achievementService.findAchievementById(id);
        if(achievement==null){
            ret.put("success", false);
            ret.put("exc", "Not Found！");
        }else {
            achievement.setId(id);
            achievement.setName(name);
            achievement.setContext(context);
            achievement.setAddtime(addtime);
            achievement.setAuthor(author);
            achievement.setLeader(leader);
            achievement.setLevel(level);
            if (useridList.size() != 0) {
                List<User> userList = new ArrayList<>();
                for (int uid : useridList) {
                    User user = userService.findUserById(uid);
                    userList.add(user);
                }
                achievement.setUserList(userList);
                //achievementService.save(achievement);
            }
            if (patentidList.size() != 0) {
                List<Patent> patentList = new ArrayList<>();
                for (int pid : patentidList) {
                    Patent patent = patentService.findById(pid);
                    patentList.add(patent);
                }
                achievement.setPatentList(patentList);
                //achievementService.save(achievement);
            }
            if (sciidList.size() != 0) {
                List<SCI> sciList = new ArrayList<>();
                for (int sid : sciidList) {
                    SCI sci = sciService.findById(sid);
                    sciList.add(sci);
                }
                achievement.setSciList(sciList);
                //achievementService.save(achievement);
            }
            achievementService.save(achievement);
            ret.put("success", true);
            ret.put("exc", "success");
        }
        return ret;
    }

    //删除成就 fix：无法解析删除
    @PostMapping("/deleteAchievement")
    public JSONObject deleteAchievement(@RequestBody JSONObject params){
        JSONObject ret=new JSONObject();
        int id=params.getInteger("id");
        if(achievementService.findAchievementById(id)==null) {
            ret.put("success", false);
            ret.put("exc", "Not Found！");
        }else{
            Achievement achievement=new Achievement();
            achievement.setId(id);
            achievementService.deleteAchievementById(id);
            ret.put("success",true);
            ret.put("exc","success");
        }
        return ret;
    }

    //查询全部成就
    @PostMapping("/findAchievementAll")
    public JSONObject findAchievementAll(@RequestBody JSONObject params){
        JSONObject ret=new JSONObject();
        if(achievementService.findAchievementAll()==null) {
            ret.put("success", false);
            ret.put("exc", "Not Found！");
        }else{
            Achievement achievement=new Achievement();
            List<Achievement> allResults = achievementService.findAchievementAll();
            int total = allResults.size();
            HashMap<String,Object> res = new HashMap<String ,Object>();
            res.put("count",total);
            res.put("data",allResults);

            ret.put("success",true);
            ret.put("exc",res);
        }
        return ret;
    }

    //通过ID查询成就
    @PostMapping("/findAchievementById")
    public JSONObject findAchievementById(@RequestBody JSONObject params){
        JSONObject ret=new JSONObject();
        int id = params.getInteger("id");
        if(achievementService.findAchievementById(id)==null) {
            ret.put("success", false);
            ret.put("exc", "Not Found！");
        }else{
            Achievement achievement=new Achievement();
            achievement = achievementService.findAchievementById(id);
            HashMap<String,Object> res = new HashMap<String ,Object>();
            res.put("count",1);
            res.put("data",achievement);
            ret.put("success",true);
            ret.put("exc",res);
        }
        return ret;
    }

    //查询成就的分页实现
    @PostMapping("/getAchievementPage")
    public JSONObject getAchievementPage(@RequestBody JSONObject params){
        JSONObject ret=new JSONObject();
        int pageNum = params.getInteger("pageNum");
        int pageSize = params.getInteger("pageSize");
        String sort = params.getString("sort");
        if(sort==null){ sort = "id"; }
        PageRequest page = PageRequest.of(pageNum, pageSize, Sort.Direction.DESC, sort);
        if(achievementService.getAchievementPage(page)==null) {
            ret.put("success", false);
            ret.put("exc", "Not Found！");
        }else{
            ret.put("success",true);
            ret.put("exc",achievementService.getAchievementPage(page));
        }
        return ret;
    }
    //查询与user，sci，patent联系，返回相关id。
    @GetMapping("/getAchievementRelate")
    public JSONObject getAchievementRelate(@RequestParam("id") int id){
        JSONObject ret=new JSONObject();
        Achievement achievement = achievementService.findAchievementById(id);
        if(achievement==null){
            ret.put("success", false);
            ret.put("exc", "Not Found！");
        }else{
            List<User> userList = achievement.getUserList();
            List<SCI> sciList=achievement.getSciList();
            List<Patent> patentList=achievement.getPatentList();
            //List<SCI> sciList=sciService.findScisByAchievement(achievement);
            //List<Patent> patentList=patentService.findPatentsByAchievement(achievement);
            List<Integer>  userid = new ArrayList<Integer>();
            List<Integer> sciid =new ArrayList<Integer>();
            List<Integer> patentid =new ArrayList<Integer>();
            List<Integer> softid=new ArrayList<>();
            for(User user:userList){
                userid.add(user.getId());
            }
            for(Patent patent:patentList){
                if(patent.getType().equals("专利"))patentid.add(patent.getId());
                else softid.add(patent.getId());
            }
            for(SCI sci:sciList){
                sciid.add(sci.getId());
            }
            HashMap<String,Object> res = new HashMap<String ,Object>();
            res.put("id",achievement.getId());
            res.put("relatedUser",userid);
            res.put("relatedPatent",patentid);
            res.put("relatedSoft",softid);
            res.put("relatedSCI",sciid);
            res.put("addtime",achievement.getAddtime());
            ret.put("success", true);
            ret.put("exc", res);
        }
        return ret;
    }

    //删除与user，sci，patent联系。
    @PostMapping("/deleteAchievementRelate")
    public JSONObject deletechievementRelate(@RequestBody JSONObject params){
        JSONObject ret=new JSONObject();
        int id = params.getInteger("id");
        Achievement achievement = achievementService.findAchievementById(id);
        List<Integer>  useridList = params.getObject("relatedUser",List.class);
        List<Integer> patentList = params.getObject("relatedPatent",List.class);
        List<Integer> sciList = params.getObject("relatedSCI",List.class);

        if(achievement==null){
            ret.put("success", false);
            ret.put("exc", "Not Found！");
        }else{
            if(useridList.size()!=0){
                for(int uid:useridList){
                    achievementService.deleteRelatedUser(id,uid);
                }
            }
            if(patentList.size()!=0){
                for(int pid:patentList){
                    achievementService.deleteRelatedPatent(id,pid);
                }
            }
            if(sciList.size()!=0){
                for(int sid:sciList){
                    achievementService.deleteRelatedSCI(id,sid);
                }
            }
            ret.put("success", true);
            ret.put("exc", "删除成功！");
        }
        return ret;
    }

    //增加与user，sci，patent联系。
    @PostMapping("/addAchievementRelate")
    public JSONObject addAchievementRelate(@RequestBody JSONObject params){
        JSONObject ret=new JSONObject();
        int id = params.getInteger("id");
        Achievement achievement = achievementService.findAchievementById(id);
        List<Integer>  useridList = params.getObject("relatedUser",List.class);
        List<Integer> patentidList = params.getObject("relatedPatent",List.class);
        List<Integer> sciidList = params.getObject("relatedSCI",List.class);

        if(achievement==null){
            ret.put("success", false);
            ret.put("exc", "Not Found！");
        }else{
            if(useridList.size()!=0){
                List<User> userList=new ArrayList<>();
                for(int uid:useridList){
                    User user=userService.findUserById(uid);
                    userList.add(user);
                }
                achievement.setUserList(userList);
                achievementService.save(achievement);
            }
            if(patentidList.size()!=0){
                List<Patent> patentList=new ArrayList<>();
                for(int pid:patentidList){
                    Patent patent=patentService.findById(pid);
                    patentList.add(patent);
                }
                achievement.setPatentList(patentList);
                achievementService.save(achievement);
            }
            if(sciidList.size()!=0){
                List<SCI> sciList=new ArrayList<>();
                for(int sid:sciidList){
                    SCI sci=sciService.findById(sid);
                    sciList.add(sci);
                }
                achievement.setSciList(sciList);
                achievementService.save(achievement);
            }
            ret.put("success", true);
            ret.put("exc", "增加成功！");
        }
        return ret;
    }

}
